import {
	jumpTo
} from '@/utils/common.js'

class Http {
	static http = new Http()
	// static baseUrl = "https://demo.soullightstheworld.com"
	static baseUrl = 'https://appapi.ivmcr.com'

	methods = ['get', 'post', 'delete', 'put']

	constructor() {
		this.initRequest()
	}

	// 请求拦截器
	async beforeReqIntercpt(options) {
		const {
			url,
			custom
		} = options

		// 设置基路由
		options.url = url[0] === '/' ? Http.baseUrl + url : '/' + url
		// console.log('🚀 ~ Http ~ beforeReqIntercpt ~ options.url:', url[0] === '/')

		// 鉴权
		if (custom?.auth) {
			const token = uni.getStorageSync('token')
			if (token) {
				options.header = {
					...options.header, // 合并其他可能存在的 header
					// Authorization: token,
					['api-token']: token,
				}
			} else {
				console.warn('Token not found')
			}
		}

		return options // 返回处理后的请求选项
	}

	// 发起请求
	sendRequest(options) {
		return new Promise((resolve, reject) => {
			uni.request({
				...options,
				success: async (res) => {
					try {
						// const result = await this.beforeResIntercpt(res) // 响应拦截器处理
						const data = res.data

						// 根据状态码判断响应
						if (data.status === 0) {
							resolve(data) // 返回数据
						} else if (data.status === 101) {
							uni.showToast({
								title: '登录过期，请重新登录',
								icon: 'none',
								success: () => {
									setTimeout(() => {
										jumpTo('/pages/login/index')
									}, 1500)
								},
							})
							reject(data)
						} else if (data.status === 500 || data.status === 1000 || data
							.status === 2000 || data
							.status === 1001 || data.status === 1002 ||
							data.status === 6002 || data.status === 6003 || data.status ===
							7311 || data.status === 7312) {
							uni.showToast({
								title: data.msg,
								icon: 'none',
								duration: 2000
							});
							resolve(data) // 返回数据

						} else if (data.status === 6001) {
							resolve(data) // 返回数据
						} else if (data.status === 6000 || data.status === 101) {
							uni.showToast({
								title: data.msg,
								icon: 'none',
								duration: 2000
							});
							// reject(data)
						} else {
							reject(data)
						}
					} catch (error) {
						reject(error)
					}
				},
				fail: (err) => reject(err),
			})
		})
	}

	// 响应拦截器
	async beforeResIntercpt(response) {
		const data = response.data

		// 根据状态码判断响应
		if (data.status === 0) {
			return data // 返回数据
		} else if (data.status === 101) {
			uni.showToast({
				title: '登录过期，请重新登录',
				icon: 'none',
				success: () => {
					setTimeout(() => {
						jumpTo('/pages/login/index')
					}, 1500)
				},
			})
			return data
		} else {
			throw new Error(`Request failed with status code: ${data.message}`)
		}
	}

	// 初始化请求
	initRequest() {
		this.methods.map((method) => {
			this[method] = async (url = '', data = {}, custom) => {
				try {
					let options = {
						url,
						method: method.toUpperCase(),
						data,
						custom,
					}
					options = await this.beforeReqIntercpt(options) // 请求拦截器
					const response = await this.sendRequest(options) // 发起请求并处理响应
					return response
				} catch (error) {
					console.error(`Error in ${method.toUpperCase()} request:`, error)
					throw error
				}
			}
		})
	}
}

export default Http.http